﻿Imports Microsoft.Win32

Public Class Form2

    Private c_objDotMatrix As clsDotMatrix
    Private c_strLastpath As String
    Private c_HighlightTopGroup As Byte
    Private c_HighlightSubGroup As Byte
    Private c_HighlightInstrument As Byte
   

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        c_objDotMatrix = clsDotMatrix.GetSingleton
        c_objDotMatrix.MaxLevels = 3
        AddHandler c_objDotMatrix.DataChanged, AddressOf ResetTree


        'dgvTopGroups.Columns.Add("tgname", "Group Name")


    End Sub



    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        ClearForm()


    End Sub


    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click

        Dim openFileDialog1 As New OpenFileDialog()


        c_strLastpath = GetPathFromRegistry()
        If c_strLastpath Is Nothing Then
            openFileDialog1.InitialDirectory = "c:\"
        Else
            openFileDialog1.InitialDirectory = System.IO.Path.GetDirectoryName(c_strLastpath)
        End If

        openFileDialog1.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"
        openFileDialog1.FilterIndex = 2
        openFileDialog1.RestoreDirectory = True

        If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Try

                OpenLibrary(openFileDialog1.FileName)
                c_strLastpath = openFileDialog1.FileName
                SetPathInRegistry(c_strLastpath)
                'write to registry
            Catch Ex As Exception
                MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
            Finally
                ' Check this again, since we need to make sure we didn't throw an exception on open.

            End Try

        End If

    End Sub

    Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click

        ClearForm()


        c_objDotMatrix.NewLibrary()
        '  cbTopGroups.SelectedIndex = 0
        txtCurrentLibraryName.Text = "<< new library >>"
        txtCurrentLibraryName.Enabled = True
        '  nudTopGroup.Value = 1


    End Sub


    Private Sub OpenLibrary(ByVal strFileName As String)

        c_objDotMatrix.LoadLibrary(strFileName)

    End Sub

    Private Sub ResetTree()

        Dim objItem As ListViewItem

        lvTopGroups.Clear()
        lvTopGroups.Columns.Add("Name", -2, HorizontalAlignment.Center)
        For Each objTopEntry As clsLibraryEntry In c_objDotMatrix.TopLevelEntries
            objItem = New ListViewItem
            objItem.Text = objTopEntry.Name
            objItem.Tag = objTopEntry
            lvTopGroups.Items.Add(objItem)
        Next
        If c_HighlightTopGroup > 0 Then
            lvTopGroups.Items(c_HighlightTopGroup - 1).Selected = True
            c_HighlightTopGroup = 0
        Else
            lvTopGroups.Items(0).Selected = True
        End If

        gboxMain.Enabled = True
        txtCurrentLibraryName.Enabled = True
        txtCurrentLibraryName.Text = c_objDotMatrix.Library.LibraryName


    End Sub


    Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
        Dim blnValidationFail As Boolean = False


        If txtCurrentLibraryName.Text = "" Or txtCurrentLibraryName.Text = "<< new library >>" Then
            MsgBox("Please enter a name for your library", MsgBoxStyle.OkOnly)
            blnValidationFail = True
        End If

        If Not blnValidationFail Then

            SelectAndSave()

        End If
    End Sub


    Private Sub SaveToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click

        Dim blnValidationFail As Boolean = False

        If txtCurrentLibraryName.Text = "" Or txtCurrentLibraryName.Text = "<< new library >>" Then
            MsgBox("Please enter a name for your library", MsgBoxStyle.OkOnly)
            blnValidationFail = True
        End If

        If Not blnValidationFail Then

            Try
                If Not c_strLastpath Is Nothing Then
                    c_objDotMatrix.SaveLibrary(c_strLastpath)
                Else
                    SelectAndSave()
                End If



                'write to registry
            Catch Ex As Exception
                MessageBox.Show("Cannot save file to disk. Original error: " & Ex.Message)
            Finally
                ' Check this again, since we need to make sure we didn't throw an exception on open.

            End Try

        End If
    End Sub


    Private Sub SelectAndSave()

        Dim saveFileDialog1 As New SaveFileDialog()
        saveFileDialog1.InitialDirectory = "c:\"
        saveFileDialog1.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"
        saveFileDialog1.FilterIndex = 2
        saveFileDialog1.RestoreDirectory = True

        If saveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Try

                c_objDotMatrix.SaveLibrary(saveFileDialog1.FileName)
                c_strLastpath = saveFileDialog1.FileName
                SetPathInRegistry(c_strLastpath)

                'write to registry
            Catch Ex As Exception
                MessageBox.Show("Cannot save file to disk. Original error: " & Ex.Message)
            Finally
                ' Check this again, since we need to make sure we didn't throw an exception on open.

            End Try

        End If
    End Sub

    Private Sub ClearForm()

        gboxMain.Enabled = False
        gboxSub.Enabled = False
        gboxInst.Enabled = False
        txtCurrentLibraryName.Enabled = False


        txtCurrentLibraryName.Text = ""


    End Sub


    Private Sub CloseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseToolStripMenuItem.Click


        'load the current library (if any)
        'compare agains the loaded library
        'check the same?
        MsgBox("TODO")

        If MsgBox("Close without saving?") = MsgBoxResult.Ok Then
            ClearForm()
        End If


    End Sub

    Private Sub txtCurrentLibraryName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCurrentLibraryName.TextChanged
        If txtCurrentLibraryName.Text.Length > 0 Then
            c_objDotMatrix.LibraryName = txtCurrentLibraryName.Text
        End If
    End Sub


    Private Sub lvTopGroups_ItemSelectionChanged(ByVal sender As Object, ByVal e As ListViewItemSelectionChangedEventArgs) Handles lvTopGroups.ItemSelectionChanged

        Dim thisTopGroup As clsLibraryEntry
        Dim objItem As ListViewItem

        If e.IsSelected Then

            thisTopGroup = CType(e.Item.Tag, clsLibraryEntry)

            lvSubGroups.Clear()
            lvSubGroups.Columns.Add("Name", -2, HorizontalAlignment.Center)
            For Each objSubEntry As clsLibraryEntry In c_objDotMatrix.SelectChildren(thisTopGroup.Level, thisTopGroup.UID)
                objItem = New ListViewItem
                objItem.Text = objSubEntry.Name
                objItem.Tag = objSubEntry
                lvSubGroups.Items.Add(objItem)
            Next
            gboxSub.Enabled = True
            If c_HighlightSubGroup > 0 Then
                lvSubGroups.Items(c_HighlightSubGroup - 1).Selected = True
                c_HighlightSubGroup = 0
            Else
                lvSubGroups.Items(0).Selected = True
            End If

        End If



    End Sub



    Private Sub lvSubGroups_ItemSelectionChanged(ByVal sender As Object, ByVal e As ListViewItemSelectionChangedEventArgs) Handles lvSubGroups.ItemSelectionChanged

        Dim thisSubGroup As clsLibraryEntry
        Dim objItem As ListViewItem
        Dim objInstrumentDetail As clsInstrument

        If e.IsSelected Then

            thisSubGroup = CType(e.Item.Tag, clsLibraryEntry)

            lvInstruments.Clear()
            lvInstruments.Columns.Add("Name", 300, HorizontalAlignment.Center)
            lvInstruments.Columns.Add("VST", -2, HorizontalAlignment.Center)
            lvInstruments.Columns.Add("fxp path", -2, HorizontalAlignment.Center)
            For Each objInstrument As clsLibraryEntry In c_objDotMatrix.SelectChildren(thisSubGroup.Level, thisSubGroup.UID)
                objItem = New ListViewItem
                objItem.Tag = objInstrument
                If Not objInstrument.Detail Is Nothing Then
                    objInstrumentDetail = CType(objInstrument.Detail, clsInstrument)
                    objItem.Text = objInstrument.Name
                    objItem.SubItems.Add(objInstrumentDetail.VSTInstrument)
                    objItem.SubItems.Add(objInstrumentDetail.fxpPath)
                Else
                    objInstrument.Detail = New clsInstrument
                    objItem.Text = objInstrument.Name
                End If

                lvInstruments.Items.Add(objItem)
            Next
            gboxInst.Enabled = True
            If c_HighlightInstrument > 0 Then
                lvInstruments.Items(c_HighlightInstrument - 1).Selected = True
                c_HighlightInstrument = 0
            Else
                lvInstruments.Items(0).Selected = True
            End If

        End If


    End Sub

    Private Function GetPathFromRegistry() As String
        Dim regPath As RegistryKey
        Dim strPath As String
        Dim strRegistryPath As String
        Dim strDefaultLibraryPath As String

        strRegistryPath = Configuration.ConfigurationSettings.AppSettings("RegistryPath")
        strDefaultLibraryPath = Configuration.ConfigurationSettings.AppSettings("DefaultLibraryPath")

        regPath = Registry.CurrentUser.OpenSubKey(strRegistryPath, True)
        If regPath Is Nothing Then
            ' Key doesn't exist; create it.
            regPath = Registry.CurrentUser.CreateSubKey(strRegistryPath)
        End If

        If (Not regPath Is Nothing) Then
            strPath = regPath.GetValue("CurrentLibrary", strDefaultLibraryPath)
            regPath.Close()
        End If

        Return strPath

    End Function

    Private Sub SetPathInRegistry(ByVal strPath As String)
        Dim regPath As RegistryKey
        Dim strRegistryPath As String

        strRegistryPath = Configuration.ConfigurationSettings.AppSettings("RegistryPath")

        regPath = Registry.CurrentUser.OpenSubKey(strRegistryPath, True)
        If regPath Is Nothing Then
            ' Key doesn't exist; create it.
            regPath = Registry.CurrentUser.CreateSubKey(strRegistryPath)
        End If

        If (Not regPath Is Nothing) Then
            regPath.SetValue("CurrentLibrary", strPath)
            regPath.Close()
        End If


    End Sub



    Private Sub btnTestDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestDisplay.Click

        frmTesting.Show()


    End Sub


    Private Sub lvTopGroups_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvTopGroups.MouseUp

        Dim ctxtMenu As New ContextMenu

        If (e.Button <> MouseButtons.Right) Then Exit Sub

        If Not lvTopGroups.GetItemAt(e.X, e.Y) Is Nothing Then
            lvTopGroups.GetItemAt(e.X, e.Y).Selected = True
            ctxtMenu = BuildSelectedTopGroupContextMenu()
            ctxtMenu.Show(lvTopGroups, New Point(e.X, e.Y))
        Else
            ctxtMenu = BuildNoSelectTopGroupContextMenu()
            ctxtMenu.Show(lvTopGroups, New Point(e.X, e.Y))

        End If
      
       
        

    End Sub

    Private Sub lvSubGroups_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvSubGroups.MouseUp

        Dim ctxtMenu As New ContextMenu


        If (e.Button <> MouseButtons.Right) Then Exit Sub

        If Not lvSubGroups.GetItemAt(e.X, e.Y) Is Nothing Then
            lvSubGroups.GetItemAt(e.X, e.Y).Selected = True
            ctxtMenu = BuildSelectedSubGroupContextMenu()
            ctxtMenu.Show(lvSubGroups, New Point(e.X, e.Y))
        Else
            ctxtMenu = BuildNoSelectSubGroupContextMenu()
            ctxtMenu.Show(lvSubGroups, New Point(e.X, e.Y))

        End If

    End Sub

    Private Sub lvInstruments_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvInstruments.MouseUp

        Dim ctxtMenu As New ContextMenu


        If (e.Button <> MouseButtons.Right) Then Exit Sub

        If Not lvInstruments.GetItemAt(e.X, e.Y) Is Nothing Then
            lvInstruments.GetItemAt(e.X, e.Y).Selected = True
            ctxtMenu = BuildSelectedInstrumentContextMenu()
            ctxtMenu.Show(lvInstruments, New Point(e.X, e.Y))
        Else
            ctxtMenu = BuildNoSelectInstrumentContextMenu()
            ctxtMenu.Show(lvInstruments, New Point(e.X, e.Y))
        End If

    End Sub


    Private Function BuildSelectedTopGroupContextMenu() As ContextMenu
        Dim ctxtMenu As New ContextMenu

        ctxtMenu.MenuItems.Add("rename", New EventHandler(AddressOf mnuRenameTopGroup_Click))
        ctxtMenu.MenuItems.Add("add top group", New EventHandler(AddressOf mnuAddTopgroup_Click))
        ctxtMenu.MenuItems.Add("delete top group", New EventHandler(AddressOf mnuDeleteTopGroup_Click))

        Return ctxtMenu

    End Function

    Private Function BuildNoSelectTopGroupContextMenu() As ContextMenu
        Dim ctxtMenu As New ContextMenu

        ctxtMenu.MenuItems.Add("add top group", New EventHandler(AddressOf mnuAddTopgroup_Click))

        Return ctxtMenu

    End Function

    Private Function BuildSelectedSubGroupContextMenu() As ContextMenu
        Dim ctxtMenu As New ContextMenu

        ctxtMenu.MenuItems.Add("rename", New EventHandler(AddressOf mnuRenameSubGroup_Click))
        ctxtMenu.MenuItems.Add("add sub group", New EventHandler(AddressOf mnuAddSubgroup_Click))
        ctxtMenu.MenuItems.Add("delete sub group", New EventHandler(AddressOf mnuDeleteSubGroup_Click))

        Return ctxtMenu

    End Function
    Private Function BuildNoSelectSubGroupContextMenu() As ContextMenu
        Dim ctxtMenu As New ContextMenu

        ctxtMenu.MenuItems.Add("add sub group", New EventHandler(AddressOf mnuAddSubgroup_Click))

        Return ctxtMenu

    End Function


    Private Function BuildSelectedInstrumentContextMenu() As ContextMenu
        Dim ctxtMenu As New ContextMenu

        ctxtMenu.MenuItems.Add("edit", New EventHandler(AddressOf mnuEditInstrument_Click))
        ctxtMenu.MenuItems.Add("delete", New EventHandler(AddressOf mnuDeleteInstrument_Click))
        ctxtMenu.MenuItems.Add("add instrument", New EventHandler(AddressOf mnuAddInstrument_Click))


        Return ctxtMenu

    End Function


    Private Function BuildNoSelectInstrumentContextMenu() As ContextMenu
        Dim ctxtMenu As New ContextMenu

        ctxtMenu.MenuItems.Add("add instrument", New EventHandler(AddressOf mnuAddInstrument_Click))

        Return ctxtMenu

    End Function


    Private Function mnuRenameTopGroup_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        lvTopGroups.LabelEdit = True
        lvTopGroups.SelectedItems(0).BeginEdit()

    End Function


    Private Function mnuRenameSubGroup_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        lvSubGroups.LabelEdit = True
        lvSubGroups.SelectedItems(0).BeginEdit()

    End Function


    Private Function mnuAddTopgroup_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim insertAfter As Byte

        If lvTopGroups.SelectedItems.Count > 0 Then
            insertAfter = CType(lvTopGroups.SelectedItems(0).Tag, clsLibraryEntry).Sort
        Else
            insertAfter = lvTopGroups.Items.Count + 1
        End If
        'insert after current item and rebuild

        c_HighlightTopGroup = insertAfter
        c_objDotMatrix.AddItem(Nothing, 1, insertAfter)


        'refreshes display when DisplayChanged event is raise - resselect index ???
    End Function


    Private Function mnuAddSubgroup_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim insertAfter As Byte
        Dim parentGuid As Guid


        parentGuid = CType(lvTopGroups.SelectedItems(0).Tag, clsLibraryEntry).UID

        If lvSubGroups.SelectedItems.Count > 0 Then
            insertAfter = CType(lvSubGroups.SelectedItems(0).Tag, clsLibraryEntry).Sort
        Else
            insertAfter = lvSubGroups.Items.Count + 1
        End If
        c_HighlightSubGroup = insertAfter
        c_HighlightTopGroup = CType(lvTopGroups.SelectedItems(0).Tag, clsLibraryEntry).Sort - 1
        'insert after current item and rebuild
        c_objDotMatrix.AddItem(parentGuid, 2, insertAfter)



        'refreshes display when DisplayChanged event is raise - resselect index ???
    End Function

    Private Function mnuAddInstrument_Click(ByVal sender As Object, ByVal e As System.EventArgs)
       
        Dim frmEdit As New frmEditInstrument
        Dim insertAfter As Byte

        Dim parentGuid As Guid


        parentGuid = CType(lvSubGroups.SelectedItems(0).Tag, clsLibraryEntry).UID

        frmEdit = New frmEditInstrument
        frmEdit.Instrument = CType(lvSubGroups.SelectedItems(0).Tag, clsLibraryEntry).Detail
        If frmEdit.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then

            If lvInstruments.SelectedItems.Count > 0 Then
                insertAfter = CType(lvInstruments.SelectedItems(0).Tag, clsLibraryEntry).Sort
            Else
                insertAfter = lvInstruments.Items.Count + 1
            End If
            'insert after current item and rebuild
            c_HighlightInstrument = insertAfter
            c_HighlightSubGroup = CType(lvSubGroups.SelectedItems(0).Tag, clsLibraryEntry).Sort - 1

            c_objDotMatrix.AddItem(parentGuid, 3, insertAfter, frmEdit.Instrument.Name, frmEdit.Instrument)

        End If

        frmEdit.Dispose()

    End Function


    Private Function mnuEditInstrument_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim frmEdit As New frmEditInstrument
        Dim parentGuid As Guid
        ' frmEdit.Show()

        parentGuid = CType(lvSubGroups.SelectedItems(0).Tag, clsLibraryEntry).UID

        frmEdit = New frmEditInstrument
        frmEdit.Instrument = CType(lvInstruments.SelectedItems(0).Tag, clsLibraryEntry).Detail
        frmEdit.Instrument.Name = CType(lvInstruments.SelectedItems(0).Tag, clsLibraryEntry).Name
        If frmEdit.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then

            'update the current item and rebuild
            c_objDotMatrix.UpdateItemDetail(CType(lvInstruments.SelectedItems(0).Tag, clsLibraryEntry).UID, frmEdit.Instrument.Name, frmEdit.Instrument)
        End If

        frmEdit.Dispose()

    End Function


    Private Function mnuDeleteInstrument_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MsgBox("delete")
    End Function


    Private Function mnuDeleteTopGroup_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MsgBox("delete")
    End Function


    Private Function mnuDeleteSubGroup_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MsgBox("delete")
    End Function

    Private Sub lvTopGroups_AfterLabelEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.LabelEditEventArgs) Handles lvTopGroups.AfterLabelEdit

        e.CancelEdit = True

        c_objDotMatrix.RenameItem(CType(lvTopGroups.SelectedItems(0).Tag, clsLibraryEntry).UID, e.Label)

    End Sub

    Private Sub lvSubGroups_AfterLabelEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.LabelEditEventArgs) Handles lvSubGroups.AfterLabelEdit

        e.CancelEdit = True
        e.CancelEdit = True

        c_objDotMatrix.RenameItem(CType(lvSubGroups.SelectedItems(0).Tag, clsLibraryEntry).UID, e.Label)

    End Sub

End Class
